#include "MaterialDictionary.h"

#include <iostream>
#include <fstream>

//#define TIXML_USE_STL
#include <tinyxml.h>

MaterialDictionary::MaterialDictionary() : numOrganics(0), numInorganics(0)
{
}

void MaterialDictionary::addInorganic(uint32_t index, std::string name)
{
    names[std::pair<uint32_t,uint16_t>(index,0)] = name;
    numInorganics++;
}

void MaterialDictionary::addOrganic(uint32_t index, std::string name)
{
    names[std::pair<uint32_t,uint16_t>(index,1)] = name;
    numOrganics++;
}

int MaterialDictionary::getNumInorganics()
{
    return numInorganics;
}

int MaterialDictionary::getNumOrganics()
{
    return numOrganics;
}

std::string MaterialDictionary::getName(uint32_t index, uint16_t type)
{
    std::pair<uint32_t,uint16_t> typePair = std::make_pair(index,type);
    if (!names.count(typePair)) return "DEFAULT";
    return names[typePair];
}

Ogre::ColourValue MaterialDictionary::getColour(uint32_t index, uint16_t type)
{
    if (names.find(std::make_pair(index,type))==names.end()) return Ogre::ColourValue(0.6,0.6,0.6);
    return getColour(names[std::make_pair(index,type)]);
}

Ogre::ColourValue MaterialDictionary::getColour(std::string name)
{
    if (colors.find(name) != colors.end()) return colors[name];
    else return Ogre::ColourValue(0.6,0.6,0.6);
}

void MaterialDictionary::loadColors(std::string path)
{
    path += "/";
    std::ifstream indexFile(path+"index.txt", std::ios::in);
    if (!indexFile.is_open()) return;
    std::string line;
    while (indexFile.good())
    {
        std::getline(indexFile,line);
        TiXmlDocument doc((path+line).c_str());
        if (!doc.LoadFile()) continue;
        TiXmlElement *root  = doc.FirstChildElement();
        TiXmlElement *color = root->FirstChildElement("color");
        while (color)
        {
            TiXmlElement *material = color->FirstChildElement("material");
            while (material)
            {
                TiXmlElement *subtype = material->FirstChildElement("subtype");
                while (subtype)
                {
                    double red=0, green=0, blue=0;
                    color->Attribute("red",&red);
                    color->Attribute("green",&green);
                    color->Attribute("blue",&blue);
                    colors[subtype->Attribute("value")] = Ogre::ColourValue((float)(red/255.0),(float)(green/255.0),(float)(blue/255.0));
                    subtype = subtype->NextSiblingElement("subtype");
                }
                material = material->NextSiblingElement("material");
            }
            color = color->NextSiblingElement("color");
        }
    }
}
